module.exports = app => {
    const express = require("express");
    const jwt = require("jsonwebtoken");
    const User = require("../models/User");
    const assert = require("http-assert");
    const router = express.Router({
      mergeParams: true
    });
  
    // const categoryModel = require("../../models/categoryModel");
    // 增==创建资源
    // router.post("/", async (req, res) => {
    //   // const modelName = require("inflection").classify(req.params.resource);
    //   // const Model = require(`../../models/${modelName}`);
    //   const model = await req.Model.create(req.body);
    //   res.send(model);
    // });
  
    
    // 资源详情 获取详情页接口
    // router.get("/:id", async (req, res) => {
    //   //限制10条
    //   // const modelName = require("inflection").classify(req.params.resource);
    //   // const Model = require(`../../models/${modelName}`);
    //   console.log("req.params.id", req.params.id);
    //   const model = await req.Model.findById(req.params.id);
    //   console.log("model:", model);
    //   res.send(model);
    // });


    // 更新资源 修改数据接口
    // router.put("/:id", async (req, res) => {
    //   // const modelName = require("inflection").classify(req.params.resource);
    //   // const Model = require(`../../models/${modelName}`);
    //   const model = await req.Model.findByIdAndUpdate(req.params.id, req.body);
    //   res.send(model);
    // });


    //删除接口
    // router.delete("/:id", async (req, res) => {
    //   // const modelName = require("inflection").classify(req.params.resource);
    //   // const Model = require(`../../models/${modelName}`);
    //   await req.Model.findByIdAndDelete(req.params.id, req.body);
    //   res.send({
    //     success: true
    //   });
    // });
  
    // 查
    router.get(
      "/",
      async (req, res) => {
        const queryOptions = {};
        if (req.Model.modelName === "category") {
          queryOptions.populate = "parent";
        }
        const items = await req.Model.find()
          .setOptions(queryOptions)
          .limit(10);
        console.log(items);
  
        res.send(items);
      }
    );
  
    // 登录校验中间件 ==>组件化
    const authMiddleware = require('../middleware/auth')
    //  自动获取模型的中间件
    const resourceMiddleware = require('../middleware/resource')

  
  
    //路由挂载 中间件 处理
    // app.use("/login/api/rest/:resource", authMiddleware, resourceMiddleware, router);
    app.use("/login/api/rest/:resource", authMiddleware(), resourceMiddleware(), router);
  
    // 上传中间件
    // const multer = require("multer");
    // const upload = multer({ dest: __dirname + "/../../uploads" });
    // 上传接口
    // app.post(
    //   "/login/api/upload",
    //   authMiddleware(),
    //   upload.single("file"),
    //   async (req, res) => {
    //     const file = req.file; //一定要加multer才有req.file
    //     file.url = `http://localhost:3000/uploads/${file.filename}`;
    //     res.send(file);
    //   }
    // );
    //ceshi
  	app.get("/", (req, res) => {
      	console.log(req.body);
    	res.send("11")
    });
    app.get("/api", (req, res) => {
      console.log(req.body);
    res.send("api")
  });

    // 用户登录
    app.post("/login", async (req, res) => {
      console.log(req.body);
      const { email, password } = req.body;
      const user = await User.findOne({ email }).select("+password");
      // 使用 http-assert
      assert(user, 422, "用户不存在");

      const isValid = require("bcryptjs").compareSync(password, user.password);
      assert(isValid, 422, "密码错误");

      const token = jwt.sign(
        {
          id: user._id
          // _id: user._id,
          // username: user.username
        },
        app.get("secret")
      );
      res.send({ token });
    });
    //用户注册
    app.post("/register", async (req, res) => {
      console.log(req.body);
      // const modelName = require("inflection").classify(req.params.resource);
      // const Model = require(`../../models/${modelName}`);
      const user = await User.create(req.body);
      res.send(user);
    });


  
    // 错误处理函数
    app.use(async (err, req, res, next) => {
      console.log(err);
      // 此处 没有500 会报错
      res.status(err.statusCode || 500).send({
        message: err.message
      });
    });
  };
  